#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import shutil
import glob
import time

import opencv.highgui as gui
import opencv.cv as cv
from opencv.adaptors import Ipl2PIL, PIL2Ipl
import PIL.Image

def convertFile(filePath, name, ext, oututQuestionFileName, outputAnswerFileName):    
    print "converting file %s"%name
    
    #yeah so lame but at least it works... damn channels!....
    img = gui.cvLoadImage(os.path.join(filePath, name+ext))
    img = PIL2Ipl(Ipl2PIL(img).transpose(PIL.Image.ROTATE_270))
    
    meaning = img[10:180, 140:200]
    kanji = img[10:87, 200:280]
    readings = img[87:180, 200:280]
    examples = img[8:180, 10:124]
    
    #create the output images
    question = cv.cvCreateImage((256, 192), 8, 3)
    answer = cv.cvCreateImage((256, 192), 8, 3)
    
    #paint them white
    question[0:192, 0:256]=[255,255,255]
    answer[0:192, 0:256]=[255,255,255]
    
    #build the question
    question[0:170, 140:200] = meaning
    question[0:93, 30:110] = readings
    
    #build the answer
    answer[50:127, 150:230] = kanji
    answer[8:180, 10:124] = examples
    
    #save output image files 16 bit bmp (~=50k each!)
    Ipl2PIL(question).convert('L').save(outputQuestionFileName+".bmp")
    Ipl2PIL(answer).convert('L').save(outputAnswerFileName+".bmp")
    
if __name__=="__main__":
    startTime = time.time()
    
    arrayOfFiles = []
    for i in xrange(0,20):
        arrayOfFiles.append([])
    
    #each subfolder contains kanjis for a specific level
    for level in xrange(1,21):
        for root, dirs, files in os.walk("..\\kanjis\\%d"%(level)):
            for f in files:
                if not (f.find("Q")!=-1 or f.find("A")!=-1):
                    name, ext = os.path.splitext(f)
                    outputQuestionFileName = "K"+name+"Q"
                    outputAnswerFileName = "K"+name+"A"
                    convertFile(os.path.abspath(root), name, ext, outputQuestionFileName, outputAnswerFileName)

                    #add the filenames in the C array to be used in the C code
                    arrayOfFiles[level-1].append("K"+name)
    
    print "Done parsing files, now writing the results to the kanjis.h file..."
    includeFile = open("kanjis.h","w")
    includeFile.write(
    """
    /* -------- WARNING
    This file has been generated automatically,
    do not nodify it manually unless you know what you are doing
    */
    """)
    includeFile.write(
    """
    /* Creation of the C arrays to display the questions
    */
    """)
    for i, arrayOfFile in enumerate(arrayOfFiles):
        includeFile.write("\nchar* q%d[] = {"%i)
        for f in arrayOfFile:
            includeFile.write(""" "%sQ.bmp" """%f)
            if f!= arrayOfFile[-1]:
                includeFile.write(",\n");
        includeFile.write("};")
    includeFile.write("\n");
    #includeFile.write("char** kanjiQuestionFiles[4] = {q0, q1, q2, q3};")
    includeFile.write("char** kanjiQuestionFiles[%d] = {"%len(arrayOfFiles))
    for i in xrange(len(arrayOfFiles)):
        if i!=len(arrayOfFiles)-1:
            includeFile.write("q%d, "%i)
        else:
            includeFile.write("q%d};"%i)
            
    
    includeFile.write(
    """
    /* Creation of the C arrays to display the images
    */
    """)
    for i, arrayOfFile in enumerate(arrayOfFiles):
        includeFile.write("\nchar* a%d[] = {"%i)
        for f in arrayOfFile:
            includeFile.write(""" "%sA.bmp" """%f)
            if f!= arrayOfFile[-1]:
                includeFile.write(",\n");
        includeFile.write("};")
    includeFile.write("\n");
   # includeFile.write("char** kanjiAnswerFiles[4] = {a0, a1, a2, a3};")
    includeFile.write("char** kanjiAnswerFiles[%d] = {"%len(arrayOfFiles))
    for i in xrange(len(arrayOfFiles)):
        if i!=len(arrayOfFiles)-1:
            includeFile.write("a%d, "%i)
        else:
            includeFile.write("a%d};"%i)
    
    #includeFile.write("\n\nint NB_KANJIS[4] ={%d, %d, %d, %d};"%(len(arrayOfFiles[0]),
    #                                                          len(arrayOfFiles[1]),
    #                                                          len(arrayOfFiles[2]),
    #                                                          len(arrayOfFiles[3])))
    includeFile.write("\n\nint NB_KANJIS[%d] = {"%len(arrayOfFiles))
    for i in xrange(len(arrayOfFiles)):
        if i!=len(arrayOfFiles)-1:
            includeFile.write("%d, "%len(arrayOfFiles[i]))
        else:
            includeFile.write("%d};"%len(arrayOfFiles[i]))
    
    
    includeFile.close()
    
    
    print "header file writing finished, now moving the files to their folders"
    #we clear the previous files and copy the one we just created
    print "moving kanjis.h"
    os.remove("..\\source\\kanjis.h")
    shutil.move("kanjis.h", "..\\source")
    
    print "moving the images..."
    #move the images
    images = glob.glob("*.bmp")
    for img in images:
        shutil.copy(img, "..\\efsroot")
        os.remove(img)
        
    print "Finished in %fsec."%(time.time()-startTime)